﻿app.factory('RoleFactory', function ($http, $window, $q) {
    return {
        getRole: function () {
            var deferred = $q.defer();
            $http({
                url: '/api/apiUserRole',
                method: "GET",
                headers: { Authorization: "Bearer " + $window.sessionStorage.getItem('token') }
            }).success(function (data) {
                $window.sessionStorage.setItem('role', data.RoleName);
                //alert(data.Username + " from GETROLE")
                deferred.resolve(data.Username);
            })
            return deferred.promise;
        }
    }
})
app.factory('LoginFactory', function ($http, $window, $q, RoleFactory) {
    return {
        loggedIn: function () {
            if ($window.sessionStorage.token) return true;
            else return false;
        },
        login: function (username, password) {
            var deferred = $q.defer();
            $http({
                url: '/Token',
                method: 'POST',
                contentType: 'application/x-www-form-urlencoded',
                data: 'username=' + username + '&password=' + password + '&grant_type=password'
            }).success(function (data) {
                $window.sessionStorage.setItem('token', data.access_token);
                RoleFactory.getRole().then(function (name) {
                    //alert(name + "From Login");
                    deferred.resolve(name);
                });
            }).error(function () {
                $window.sessionStorage.removeItem('token');
                deferred.reject();
            });
            return deferred.promise;
        },
        logout: function () {
            $window.sessionStorage.removeItem('token');
        }
    }
})